package edu.ctbu.insurance.service.impl;

import edu.ctbu.insurance.bean.User;
import edu.ctbu.insurance.mapper.UserMapper;
import edu.ctbu.insurance.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author djl
 * @since 2024-06-28
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final Object lock = new Object(); // 用于同步的锁对象
    private final Random random = new Random(System.currentTimeMillis()); // 使用当前时间戳作为种子

    @Autowired
    private UserMapper userMapper;

    @Override
    public String createUser() {
        synchronized (lock) { // 进入同步代码块
            StringBuilder accountBuilder = new StringBuilder();
            List<User> userList = userMapper.selectList(null);

            boolean flag = true;
            while (flag) {
                for (int i = 0; i < 8; i++) {
                    // 生成0-9之间的随机数，并追加到账号构建器中
                    accountBuilder.append(random.nextInt(10));
                }
                flag = false;
                for (User value : userList) {
                    if (value.getUserAccount().contentEquals(accountBuilder)) {
                        flag = true;
                        break;
                    }
                }
            }

            return accountBuilder.toString();
        }
    }

    @Override
    public boolean login(String userAccount, String userPwd) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_account", userAccount);
        map.put("user_pwd", userPwd);

        List<User> userList = userMapper.selectByMap(map);
        return !userList.isEmpty();
    }

    @Override
    public List<User> getUserByEmail(String email) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_email", email);

        return userMapper.selectByMap(map);
    }


}
